#include "user_register_widget.h"
#include "ui_user_register_widget.h"

#include "error_codes.h"

#include <QMessageBox>

#include "user_register.pb.h"
#include "network_message.h"

UserRegisterWidget::UserRegisterWidget(QWidget *parent, std::shared_ptr<tcp_client> client) :
    QDialog(parent),
    ui(new Ui::UserRegisterWidget),
    clientPtr(client)
{
    ui->setupUi(this);

    /* 用户点击登录按钮事件处理 */
    connect(ui->registerPushButton, &QPushButton::clicked, this, [this]() {
        auto userName = ui->userNameLineEdit->text();
        auto passwd = ui->passWordLineEdit->text();
        qDebug() << "user name:" << userName << "password" << passwd;

        int ret = onUserRegister(userName, passwd);
        if (ret == EC_NOT_CONNECTED) {
            qDebug() << "not connected";
            ui->errorMsgLabel->setText("连接服务器失败，请检查网络连接。");
        } else if (ret != EC_OK) {
            qDebug() << "user login failed";
            ui->errorMsgLabel->setText("登录失败，请检查用户名密码是否正确。");
        }
    });

    /* 用户点击去登录按钮事件 */
    connect(ui->toLoginPushButton, &QPushButton::clicked, this, [this]() {
        close();
    });

}

UserRegisterWidget::~UserRegisterWidget()
{
    delete ui;
}

int UserRegisterWidget::onUserRegister(const QString &username, const QString &passwd)
{
    /* 构造登录消息 */
    UserRegisterC2SProto registerMsg;
    registerMsg.set_name(username.toStdString());
    registerMsg.set_password(passwd.toStdString());

    std::cout << registerMsg.DebugString() << std::endl;

    std::string protobufStr;
    bool ret = registerMsg.SerializeToString(&protobufStr);
    if (!ret) {
        qDebug() << "serialize register message failed";
        return EC_PROTOBUF_SEARILIZE_FAILED;
    }

    network_message msg(MSG_TYPE_C2S_USER_REGISTER, protobufStr);
    auto msgToSend = msg.to_string();
    return clientPtr->send_message(msgToSend);
}

int UserRegisterWidget::onUserRegisterResponse(int result, const QString &responseMsg)
{
    if (result != 0) {
        qDebug() << "user register failed: " << responseMsg;
        ui->errorMsgLabel->setText(QString("注册失败: ") + responseMsg);

        return EC_LOGIN_FAILED;
    }

    ui->errorMsgLabel->setText(QString("注册成功，快去登录吧") + responseMsg);

    return EC_OK;
}
